package com.myx.typhoon.web.security;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import com.myx.typhoon.business.domain.User;
import com.myx.typhoon.common.util.RegexUtil;
import com.myx.typhoon.sys.service.UserService;

/**  
 * @author myx
 * @createTime 2016年2月2日 下午3:30:19  
 * 
 */
public class ShiroDataBaseRealm extends AuthorizingRealm{
	
	@Resource
	private UserService userService;

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(
			PrincipalCollection principals) {
		SimpleAuthorizationInfo info = null;
		if(principals != null) {
			info = new SimpleAuthorizationInfo();
			//默认授予登录用户角色
			info.addRole("LOGIN_USER");
			return info;
		}
		return null;
	}

	/**
	 * 用户认证
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken token) throws AuthenticationException {
		UsernamePasswordToken userToken = (UsernamePasswordToken) token;
		String username = userToken.getUsername();
		if(StringUtils.isNotBlank(username)) {
			User user = null;
			if(RegexUtil.checkMail(username)) {
				user = userService.findUserByEmail(username);
			}else {
				user = userService.findUserByUserName(username);
			}
			if(user != null) {
				return new SimpleAuthenticationInfo(user, user.getPassword(), getName());
			}
		}
		return null;
	}

}
